import { Component, Inject, OnInit, ViewEncapsulation } from '@angular/core';
import { RestService } from '../../services/rest.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog, MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';

@Component({
  selector: 'app-userinfo-dialog',
  templateUrl: './userinfo-dialog.component.html',
  styleUrls: ['./userinfo-dialog.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class UserinfoDialogComponent implements OnInit {
  contentHeight = 'auto';
  userForm: FormGroup;

  constructor(
    public dialogRef: MatDialogRef<UserinfoDialogComponent>,
    private restService: RestService,
    @Inject(MAT_DIALOG_DATA) private dialogData: any,
    fb: FormBuilder) {

    this.userForm = fb.group({
      name: [
        '',
        [
          Validators.required,
          Validators.minLength(4)
        ]
      ],
      password: [
        '',
        [
          Validators.required,
          Validators.minLength(4)
        ]
      ],
      password1: [
        '',
        [
          Validators.required,
          Validators.minLength(4)
        ]
      ],
      desc: [ '', [] ],
      tel: [ '', [] ],
      email: [ '', [] ],
      role: [
        'USER',
        [
          Validators.required,
        ]
      ],
    });
  }

  submit() {
    const name$ = this.userForm.controls['name'];
    const password$ = this.userForm.controls['password'];
    const password1$ = this.userForm.controls['password1'];
    const desc$ = this.userForm.controls['desc'];
    const tel$ = this.userForm.controls['tel'];
    const email$ = this.userForm.controls['email'];
    const role$ = this.userForm.controls['role'];

    this.restService.post('user', {
      name: name$.value,
      password: password$.value,
      desc: desc$.value,
      tel: tel$.value,
      email: email$.value,
      role: role$.value
    }).subscribe(data => {
      console.log('succeeded!');
      this.dialogRef.close(data);
    }, error => {
      console.error('failed to add user!');
      this.dialogRef.close(null);
    });
  }

  ngOnInit() {
  }
}
